package com.ktwlsoft.fundmanage.fundFlow.processHandler.FundOutServiceTask;

import com.ktwlsoft.fundmanage.domain.entity.FundInRecord;
import com.ktwlsoft.fundmanage.domain.entity.FundSuperviseAccept;
import com.ktwlsoft.fundmanage.domain.entity.TransferApply;
import com.ktwlsoft.fundmanage.fundFlow.processHandler.BaseServiceTask;
import com.ktwlsoft.fundmanage.payload.BaseResult;
import com.ktwlsoft.fundmanage.payload.ResultType;
import com.ktwlsoft.fundmanage.payload.exceptions.BusinessError;
import com.ktwlsoft.fundmanage.payload.fundOut.TransactRequest;
import org.activiti.engine.delegate.DelegateExecution;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;

/**
 * 生成划款单数据
 *
 * @author LanJian
 */
@Service
public class GenerateTransferApply extends BaseServiceTask {

    @Override
    public void execute(DelegateExecution execution) {
        TransactRequest transferApplyRequest = (TransactRequest) execution.getVariable("transferApply");

        FundSuperviseAccept fundSuperviseAccept = fundInService.findBusinessByTsCode(transferApplyRequest.getTsCode());
        if (transferApplyRequest.getTransactType() == TransferApply.TransferType.REFUND) {
            fundSuperviseAccept.setRefundState(FundSuperviseAccept.RefundState.WAIT_AUTH);
        }
        FundInRecord fundInRecord = fundInService.findFundInResult(transferApplyRequest.getFCode());
        int cmResult = transferApplyRequest.getAmount().compareTo(fundInRecord.getAmount());
        if (cmResult == 0) {
            fundInRecord.setTransferd(true);
        } else if (cmResult > 0) {
            throw new BusinessError("资金录入：已划走金额大于总金额！");
        } else {
            fundInRecord.setTransferd(false);
        }
        fundInRecord.setHasTransfer(fundInRecord.getHasTransfer().add(transferApplyRequest.getAmount()));
        BaseResult<TransferApply> br = fundOutService.saveTransferApply(transferApplyRequest, execution.getProcessInstanceId());
        if (br.getResultType() != ResultType.BUSINESS_SUCCESS) {
            throw new BusinessError(br.getMessage());
        } else {
            fundSuperviseAccept.setAmountLeft(fundSuperviseAccept.getAmountLeft().subtract(transferApplyRequest.getAmount()));
            if (fundSuperviseAccept.getAmountLeft().compareTo(BigDecimal.ZERO) < 0) {
                throw new BusinessError("案件：可划款金额为负数！");
            }
            TransferApply transferApply = (TransferApply) br.getData();
            fundInRecord.setDnCode(transferApply.getId());
            execution.setVariable("transferApply", transferApply);
            execution.setVariable("transferId", transferApply.getId());
        }
    }
}
